<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class CustomerAppletsCoupons extends Model
{
    protected $table      = "customerapplets_coupons";
    protected $primaryKey = "id";

    /**
     * 创建卡券数据
     * @param $couponData
     * @return array
     */
    public function createCoupon($couponData){
        DB::beginTransaction();
        try{
            $coupon['store_id']                 = $couponData['store_id'];
            $coupon['stock_id']                 = $couponData['stock_id'];
            $coupon['coupon_type']              = $couponData['coupon_type'];
            $coupon['coupon_stock_name']        = $couponData['coupon_stock_name'];
            $coupon['coupon_belong_merchant']   = $couponData['coupon_belong_merchant'];
            $coupon['coupon_comment']           = $couponData['coupon_comment'];
            $coupon['goods_name']               = $couponData['goods_name'];
            $coupon['coupon_stock_type']        = $couponData['coupon_stock_type'];
            $coupon['out_request_no']           = $couponData['out_request_no'];
            $coupon['coupon_code_mode']         = $couponData['coupon_code_mode'];
            $coupon['available_begin_time']     = $couponData['available_begin_time'];
            $coupon['available_end_time']       = $couponData['available_end_time'];
            $coupon['discount_amount']          = $couponData['discount_amount'];
            $coupon['transaction_minimum']      = $couponData['transaction_minimum'];
            $coupon['use_method']               = 1;
            $coupon['max_amount']               = $couponData['max_amount'];
            $coupon['max_coupons']              = $couponData['max_coupons'];
            $coupon['max_coupons_per_user']     = $couponData['max_coupons_per_user'];
            $coupon['coupon_source']            = 1;
            $coupon['created_at']               = $couponData['created_at'];
            $coupon['updated_at']               = $couponData['created_at'];
            $coupon['status']                   = $couponData['status'];
            $this->insert($coupon);
            DB::commit();
            return ["status" => 200,'message' => "创建成功"];
        }catch (\Exception $e){
            DB::rollBack();
            return ["status" => 202,'message' => $e->getMessage()];
        }
    }

    /**
     * 查询门店下面的卡券
     * @param $store_id 门店id
     * @param $status   卡券状态
     * @return mixed
     */
    public function getStoreCoupon($store_id,$status = ""){
        $date = date("Y-m-d H:i:s",time());
        if(!empty($status)){
            if($status == 1){
                //商家卡券状态进行中的
                $couponResult = $this
                    ->select("id","store_id","stock_id","coupon_type","coupon_stock_name","coupon_comment","goods_name","out_request_no","available_begin_time","available_end_time","discount_amount","transaction_minimum")
                    ->where(['store_id' => $store_id,'coupon_source' => 1])
                    ->where('available_end_time','>',$date)
                    ->get();
            }else{
                //商家卡券状态已失效的
                $couponResult = $this
                    ->select("id","store_id","stock_id","coupon_type","coupon_stock_name","coupon_comment","goods_name","out_request_no","available_begin_time","available_end_time","discount_amount","transaction_minimum")
                    ->where(['store_id' => $store_id,'coupon_source' => 1])
                    ->where('available_end_time','<=',$date)
                    ->get();
            }
        }else{
            $couponResult = $this
                ->select("id","store_id","stock_id","coupon_type","coupon_stock_name","coupon_comment","goods_name","out_request_no","available_begin_time","available_end_time","discount_amount","transaction_minimum")
                ->where(['store_id' => $store_id,'coupon_source' => 1])
                ->where('available_end_time','>',$date)
                ->get();
        }
        return $couponResult;
    }

    // 查询条件
    private function getMap($input)
    {
        $map = [];
        // coupon_type 1:微信支付商家券 2：微信支付代金券 3：公众号（普通优惠券）
        $map['a.coupon_type'] = 2;
        // coupon_source 卡券来源：1：微信 2:支付宝
        $map['a.coupon_source'] = 1;

        $map['a.is_delete'] = 1;

        // // 是否商户（商户删除的券不显示）
        // if (!empty($input['is_merchant'])) {
        //     $map['a.is_delete'] = 1;
        // }

        // 门店id
        if (!empty($input['store_id'])) {
            $map['a.store_id'] = $input['store_id'];
        }
        // 批次号
        if (!empty($input['stock_id'])) {
            $map['a.stock_id'] = $input['stock_id'];
        }
        // 代金券名称
        if (!empty($input['coupon_stock_name'])) {
            $map['a.coupon_stock_name'] = $input['coupon_stock_name'];
        }
        // 代金券类型（目前只支持固定面额满减券批次：NORMAL）
        if (!empty($input['coupon_stock_type'])) {
            $map['a.coupon_stock_type'] = $input['coupon_stock_type'];
        }
        // 券有效期开始时间
        if (!empty($input['available_begin_time'])) {
            $map[] = ['a.available_begin_time', '>=', $input['available_begin_time']];
        }
        // 券有效期结束时间
        if (!empty($input['available_end_time'])) {
            $map[] = ['a.available_end_time', '<=', $input['available_end_time']];
        }
        // 创建开始时间
        if (!empty($input['created_at_begin'])) {
            $map[] = ['a.created_at', '>=', $input['created_at']];
        }
        // 创建结束时间
        if (!empty($input['created_at_end'])) {
            $map[] = ['a.created_at', '<=', $input['available_begin_time']];
        }

        return $map;
    }

    // 数据个数
    public function getCashCouponCount($input)
    {
        $map = $this->getMap($input);

        return $this->from('customerapplets_coupons as a')->where($map)->count();
    }

    // 代金券列表
    public function getStoreCashCouponPageList($input, $start, $limit)
    {
        $map = $this->getMap($input);

        return $this->from('customerapplets_coupons as a')->where($map)
            ->leftjoin('customerapplets_coupon_users as b', function ($join) {
                $join->on('a.stock_id', '=','b.stock_id')
                    // ->on('a.consume_mchid', '=','b.consume_mchid')
                    ->where('b.is_use_coupon', '=', '1');
            })
            ->leftjoin('stores as c', 'a.store_id', '=', 'c.store_id')
            ->selectRaw('a.*, count(b.id) as used_num, c.store_name')
            ->groupBy('a.id')
            ->orderBy('a.status')
            ->orderBy('a.created_at', 'desc')
            ->skip($start)->limit($limit)
            ->get();
    }

    private function getCashCouponMap($input)
    {
        $map = [];

        // 门店id
        if (!empty($input['store_id'])) {
            $map['a.store_id'] = $input['store_id'];
        }
        // 批次号
        if (!empty($input['stock_id'])) {
            $map['a.stock_id'] = $input['stock_id'];
        }

        return $map;
    }

    /**
     * 获取微信代金券领用、核销数量、总数量
     */
    public function getCashCouponDetailCount($input)
    {
        $map = $this->getCashCouponMap($input);

        return $this->from('customerapplets_coupons as a')->where($map)
            ->leftjoin('customerapplets_coupon_users as b', function ($join) {
                $join->on('a.stock_id', '=','b.stock_id')
                    ->on('a.store_id', '=','b.store_id');
            })
            ->selectRaw("
                sum(IF(b.is_use_coupon = '1', 1, 0)) AS total_used_num, count(b.id) AS total_sent_num, 
                a.max_coupons
            ")
            ->first();
    }

    // 插入数据
    public function insertData($data)
    {
        return $this->insert($data);
    }

    // 审核微信代金券
    public function updateWechatCoupon($id, $data)
    {
        return $this->where('id', $id)->update($data);
    }

    // 删除微信代金券
    public function deleteWechatCoupon($id)
    {
        return $this->where('id', $id)->delete();
    }

}
